# from email.mime import image
import io
import base64
from flask import Flask, request, render_template, send_file, jsonify, Response
import simplejson as json
import os
import numpy as np
from PIL import Image
import base64
from io import BytesIO
import whisper
from clip_utils import calculate_cosine

app = Flask(__name__)
from flask_cors import CORS

CORS(app, supports_credentials=True)
# 大概有这几种模型可以使用
# ['tiny.en', 'tiny', 'base.en', 'base', 'small.en', 'small', 'medium.en', 'medium', 'large-v1', 'large-v2', 'large-v3', 'large']
# 提前加载好模型
model = whisper.load_model("small", download_root=os.path.join(os.path.dirname(__file__), "model"))

@app.route('/')  # 代表首页
def index():  # 视图函数
    # y=[]
    # x=1
    # y.append([x])
    return render_template('register.html')


@app.route("/encoder", methods=['POST'])
def encoder():
    try:
        score = 100
        mp3 = request.files.get("file")  # 获取音频文件
        url = request.values.get("url")
        answer = request.values.get("answer")
        mp3_path = os.path.join(os.path.dirname(__file__), "static", mp3.filename)
        mp3.save(mp3_path)  # 首先

        # 将mp3 文件保存成 wav格式

        result = model.transcribe(mp3_path)
        text = result["text"]
        result = calculate_cosine([text, answer, "a photo of cat"], url)
        print(result)
        #
        score = int(result[0][0] * 100.0)
        if (score <=0):
            score = np.random.randint(0, 10)

        # if(score<0.02):
        #     score = np.random.randint(0,10)
        # elif(score>0.02 and score<0.1):
        #     score = np.random.randint(0, 10)
        data = {
            "score": score,
            "content": text
        }

        return Response(json.dumps(data), mimetype='application/json')

        # confThreshold = request.values.get("confThreshold")
        # iouThreshold = request.values.get("iouThreshold")
        # print(model)
        # print(image_path)
        # print(confThreshold)
        # print(iouThreshold)
        # # opt = parse_opt(model_path=model, source=image_path, output_path='out_img',conf_thres=confThreshold,iou_thres=iouThreshold) # 配置参数
        # check_requirements(exclude=('tensorboard', 'thop')) # 校验

        # result = run(**vars(opt))
        # print(result)
        # # array = result.astype(np.uint8)  # 转换成无符号8位整型
        #
        # # 将NumPy数组转换成PIL图片对象
        # image = Image.open(result)
        #
        # # 创建一个字节流
        # buffer = BytesIO()
        #
        # # 将图片保存到字节流中，格式为PNG
        # image.save(buffer, format="JPEG")
        #
        # # 获取字节流的内容
        # img_str = buffer.getvalue()
        #
        # # 将字节流编码成base64字符串
        # img_base64 = base64.b64encode(img_str)
        #
        # # 将base64编码的数据解码成字符串
        # img_base64_str = img_base64.decode('utf-8')

        return score  # 返回得分系统
        # image_path = os.path.join(os.path.dirname(__file__), "static")
        # 解码base64数据
        # image_data = base64.b64decode(image)

        # image.save(image_path) # 首先
        # file = request.files.get("file")
        # file_path = os.path.join(os.path.dirname(__file__), "static", f"result_{predict.generate_random_str(10)}.jpg")
        # file.save(file_path)
    except Exception as e:
        print(e)
        return {
            "status": 0,
            "error": f"后端报错:{e}"
        }


app.config['DEBUG'] = True

if __name__ == '__main__':
    # 0.0.0.0代表任何能代表这台机器的地址都可以访问
    app.run(host='0.0.0.0', port=5000)  # 运行程序
    # http://8.133.188.11:5000/
